<template>
    <div>
        <a-spin :spinning="spinning">
        <div id="topbar">
            <div class="file_upload_box">
            <input id="uploadBtn" type="file" @change="loadExcel" />
            <a href="#none">上传文件</a>
            </div>
            <!-- <select v-model="selected" @change="selectExcel">
            <option disabled value="">Choose</option>
            <option v-for="option in options" :key="option.text" :value="option.value">
                {{ option.text }}
            </option>
            </select> -->
            <div>
            <a-button size="larger" @click="downloadExcel" style="margin-left: 300px; margin-top: 10px;">下载到本地</a-button>
            </div>
            <div>
            <a-button @click="save" style="margin-left: 800px; margin-top: 10px;">保存</a-button>
            </div>
        </div>
        </a-spin>
        <div id="luckysheet"></div>
        <div v-show="isMaskShow" id="tip">Downloading</div>

        <a-modal v-bind:open="visible" @ok="handleSave" @cancel="handleCancel" :confirm-loading="confirmLoading">
            <a-form
                :model="formState"
                :rules="rules"
                name="basic"
                :label-col="{ span: 8 }"
                :wrapper-col="{ span: 14 }"
                autocomplete="off"
                @finish="handleSave"
            >
                <a-form-item
                    label="角色名"
                    name="characterName"
                >
                    <a-input v-model:value="formState.characterName" placeholder="角色名"/>
                </a-form-item>
                <a-form-item
                    label="角色唯一标识名"
                    name="name"
                >
                    <a-input v-model:value="formState.name" placeholder="角色唯一标识名，不可与其他角色的唯一标识名重复"/>
                </a-form-item>
                <a-form-item
                    label="骰娘记录属性"
                    name="rememberedVars"
                >
                    <a-textarea v-model:value="formState.rememberedVars" placeholder="骰娘记录属性"/>
                </a-form-item>
                <a-form-item :wrapper-col="{ span: 14, offset: 10 }">
                    <a-button type="primary" html-type="submit">保存</a-button>
                </a-form-item>
            </a-form>
            <template #footer>
            </template>
        </a-modal>
    </div>
  </template>
    
  <script lang="js">
    export default {
      name: 'CharacterComponenet',
    }
  </script>
  
  <script lang="js" setup>
  import { reactive, ref, watch, VueElement, h, onMounted, defineProps } from 'vue';
  import { MenuProps, ItemType, Modal } from 'ant-design-vue';
  import { exportExcel, saveExcel } from './export'
  import LuckyExcel from 'luckyexcel'
  import { getCharacterList, getCharacterDetail, saveCharacter } from '../../api/character_api'
  
  const username = ref("") // 用户名
  const spinning = ref(false)
  const props = defineProps(['id'])
  
  // 初始化
  onMounted(async () => {
    spinning.value = true
    const storedValue = localStorage.getItem('username');
    if (storedValue) {
      username.value = storedValue + '的角色'
    }
    await getCharacterDetail(props.id)
      .then(async resp => {
        formState.id = resp.data.id
        formState.characterName = resp.data.characterName
        formState.rememberedVars = resp.data.rememberedVars
        formState.name = resp.data.name
        console.log(resp.data.excelUrl)
        await setTimeout(() => {
          loadExcelFromUrl(resp.data.excelUrl)
        }, 2000);
      })
  })
  
  
  const isMaskShow = ref(false)
  const selected = ref('')
  const jsonData = ref({})
  const visible = ref(false) // 保存角色的model是否可见
  const formState = reactive({// 表格对象
    id: 0,  
    characterName: '',
    name: '',
    rememberedVars: '',
  }); // 保存角色的表单
  const rules = { // 表格校验规则
    characterName: [{ required: true, message: '请输入角色名', trigger: 'blur' }],
    name: [{required: true, message:'请输入唯一角色名', trigger: 'blur'}],
  }; // 保存角色的表单的规则
  
  const loadExcelFromUrl = (url) => {
    let file = null
    getFileFromUrl(url,"tmp.xlsx")
    .then((response)=>{
        file = response
        LuckyExcel.transformExcelToLucky(file, function (exportJson, luckysheetfile) {
          if (exportJson.sheets == null || exportJson.sheets.length == 0) {
            alert('Failed to read the content of the excel file, currently does not support xls files!')
            return
          }
          console.log('exportJson', exportJson)
          jsonData.value = exportJson
      
          window.luckysheet.destroy()
      
          window.luckysheet.create({
            container: 'luckysheet', //luckysheet is the container id
            showinfobar: false,
            data: exportJson.sheets,
            title: exportJson.info.name,
            userInfo: exportJson.info.name.creator
          })
        })
        spinning.value = false
    })
    .catch((e)=>{
      console.error(e)
    });
  } // 从oss的url中获取excel并导入
  
  const loadExcel = (evt) => {
    const files = evt.target.files
    console.log(files[0])
    if (files == null || files.length == 0) {
      alert('No files wait for import')
      return
    }
  
    let name = files[0].name
    let suffixArr = name.split('.'),
    suffix = suffixArr[suffixArr.length - 1]
    if (suffix != 'xlsx') {
      alert('Currently only supports the import of xlsx files')
      return
    }
    LuckyExcel.transformExcelToLucky(files[0], function (exportJson, luckysheetfile) {
      if (exportJson.sheets == null || exportJson.sheets.length == 0) {
        alert('Failed to read the content of the excel file, currently does not support xls files!')
        return
      }
      console.log('exportJson', exportJson)
      jsonData.value = exportJson
  
      window.luckysheet.destroy()
  
      window.luckysheet.create({
        container: 'luckysheet', //luckysheet is the container id
        showinfobar: false,
        data: exportJson.sheets,
        title: exportJson.info.name,
        userInfo: exportJson.info.name.creator
      })
    })
  }
  
  const downloadExcel = () => {
    // const value = selected.value;;
    //
    // if(value.length==0){
    //     alert("Please select a demo file");
    //     return;
    // }
    //
    // var elemIF = document.getElementById("Lucky-download-frame");
    // if(elemIF==null){
    //     elemIF = document.createElement("iframe");
    //     elemIF.style.display = "none";
    //     elemIF.id = "Lucky-download-frame";
    //     document.body.appendChild(elemIF);
    // }
    // elemIF.src = value;
    exportExcel(luckysheet.getAllSheets(), '下载')
  }
  
  const save = () => {
    visible.value = true
  }
  
  const handleSave = (value) => {
    saveCharacter(formState)
    .then(resp => {
      saveExcel(luckysheet.getAllSheets(), resp.data.id)
      visible.value = false
      if (formState.id == 0) {
        items[0].children.push(getItem(resp.data.name, resp.data.id))
      }
    })
    .catch(error => {
      message.error('接口错误！')
    })
  }
  
  const handleCancel= () => {
    visible.value = false
  }
  
  const getFileFromUrl= (url, fileName) => {
    return new Promise((resolve, reject) => {
        var blob = null;
        var xhr = new XMLHttpRequest();
        xhr.open("GET", url);
        xhr.setRequestHeader('Accept', 'image/png');
        xhr.responseType = "blob";
        // 加载时处理
        xhr.onload = () => {
          // 获取返回结果
            blob = xhr.response;
            let file= new File([blob], fileName, { type: 'image/png' });
            // 返回结果
            resolve(file);
        };
        xhr.onerror = (e) => {
            reject(e)
        };
        // 发送
        xhr.send();
    });
  }
  </script>
  
  <style lang="scss" scoped>
  #luckysheet {
      margin: 0px;
      padding: 0px;
      width:  1200px;
      height: 650px;
      left: 0px;
      bottom: 0px;
      position: absolute;
      margin-top: 300px;
    }
    
    #uploadBtn {
      font-size: 16px;
    }
    
    #tip {
      position: absolute;
      z-index: 1000000;
      left: 0px;
      top: 0px;
      bottom: 0px;
      right: 0px;
      background: rgba(255, 255, 255, 0.8);
      text-align: center;
      font-size: 40px;
      align-items: center;
      justify-content: center;
      display: flex;
    }
  
    #topbar{
      display: grid; 
      grid-template-columns: 15% 15% 70%;
      grid-template-rows: 100%;
  
    }
  
  .file_upload_box {
      display: inline-block;
      width: 200px;
      height: 60px;
      position: relative;
      overflow: hidden;
  }
  .file_upload_box input[type=file] {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      line-height: 60px;
      opacity: 0;
      cursor: pointer;
  }
  .file_upload_box a {
      display: inline-block;
      width: 100%;
      line-height: 45px;
      text-align: center;
      font-family: "Microsoft yahei";
      color: black;
      font-weight: 700;
      text-decoration: none;
  }
  </style>